#!/bin/bash
exec 1>/tmp/rc.local.log 2>&1
set -euo pipefail

GADGET_NAME=fatusb
LANGUAGE=0x409 # English
MANUFACTURER="Yunlu Inc"
PRODUCT="secure usb"
SERIAL_NUM="ilikeplaywangzhe"
CONFIGFS="/sys/kernel/config/usb_gadget/"
ID_VENDOR="0x04b3"
ID_PRODUCT="0x4010"

SERIAL="$(grep Serial /proc/cpuinfo | sed 's/Serial\s*: 0000\(\w*\)/\1/')"
MAC="$(echo ${SERIAL} | sed 's/\(\w\w\)/:\1/g' | cut -b 2-)"
MAC_HOST="12$(echo ${MAC} | cut -b 3-)"
MAC_DEV1="02$(echo ${MAC} | cut -b 3-)"
MAC_DEV2="03$(echo ${MAC} | cut -b 3-)"

if [[ $EUID -ne 0 ]]; then
	echo "This script must be run as root"
	exit 1
fi

if [ ! -d $CONFIGFS ]; then
	modprobe libcomposite
fi

# Enter ConfigFS
cd $CONFIGFS

mkdir ./$GADGET_NAME && cd ./$GADGET_NAME

# Basic info

echo $ID_VENDOR 	> idVendor  # Linux Foundation
echo $ID_PRODUCT 	> idProduct # Multifunction Composite Gadget
echo 0x0100 		> bcdDevice # v1.0.0
echo 0x0200 		> bcdUSB    # USB 2.0

mkdir -p strings/$LANGUAGE
echo  $SERIAL_NUM> strings/$LANGUAGE/serialnumber
echo $MANUFACTURER > strings/$LANGUAGE/manufacturer
echo $PRODUCT > strings/$LANGUAGE/product

# # Config 1: RNDIS
# Configuring gadget as composite device
echo 0xEF > bDeviceClass
echo 0x02 > bDeviceSubClass
echo 0x01 > bDeviceProtocol

mkdir -p configs/c.1/strings/$LANGUAGE
echo "0x80" > configs/c.1/bmAttributes
echo 250 > configs/c.1/MaxPower
echo "Config 1: RNDIS network" > configs/c.1/strings/$LANGUAGE/configuration

echo "1" > os_desc/use
echo "0xcd" > os_desc/b_vendor_code
echo "MSFT100" > os_desc/qw_sign

mkdir -p functions/rndis.usb0
echo $MAC_DEV1 > functions/rndis.usb0/dev_addr
echo $MAC_HOST > functions/rndis.usb0/host_addr
echo "RNDIS" > functions/rndis.usb0/os_desc/interface.rndis/compatible_id
echo "5162001" > functions/rndis.usb0/os_desc/interface.rndis/sub_compatible_id
ln -s functions/rndis.usb0 configs/c.1

# Config 2: Serial Adapter
mkdir -p configs/c.2/strings/$LANGUAGE
echo "Config 2: Serial adapter" > configs/c.2/strings/$LANGUAGE/configuration
echo 250 > configs/c.2/MaxPower
mkdir -p functions/acm.gs0
ln -s functions/acm.gs0 configs/c.2

# Config 3: CDC ECM
mkdir -p configs/c.3/strings/$LANGUAGE
echo "Config 3: ECM network" > configs/c.3/strings/$LANGUAGE/configuration
echo 250 > configs/c.3/MaxPower

mkdir -p functions/ecm.usb0
echo $MAC_HOST > functions/ecm.usb0/host_addr
echo $MAC_DEV2 > functions/ecm.usb0/dev_addr
ln -s functions/ecm.usb0 configs/c.3

udevadm settle -t 5 || true
ls /sys/class/udc > UDC